﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Framework;
using System.IO;

namespace CanSWAT
{
    public partial class CanSWATSetupFrm : Form
    {
        public CanSWATSetupFrm()
        {
            InitializeComponent();
        }

        private ArcSWAT.Project _prj = null;
        private IApplication _app = null;
        private bool _spatialAnalystExtention = false;

        public IApplication App
        {
            set { _app = value; }
        }

        public bool SpatialAnalystExtentionAvailability
        {
            set { _spatialAnalystExtention = value; }
        }

        private void CanSWATSetupFrm_Load(object sender, EventArgs e)
        {
            if (_app != null)
            {
                _prj = new ArcSWAT.Project(_app);
                _prj.ProgressChanged += new EventHandler(onProjectProgressChanged);
                if (!_prj.IsValid)
                    _prj = null;
                else
                {
                    //save current path
                    Properties.Settings.Default.PreviousProjectFolder = 
                        _prj.ProjectFolder;
                    Properties.Settings.Default.Save();
                }
            }

            //project status
            if (_prj == null)
            {
                string previousProjectPath = Properties.Settings.Default.PreviousProjectFolder;
                if (previousProjectPath != null && System.IO.Directory.Exists(previousProjectPath))
                {
                    _prj = new ArcSWAT.Project(previousProjectPath);
                    _prj.ProgressChanged += new EventHandler(onProjectProgressChanged);
                    if (!_prj.IsValid)
                        _prj = null;

                    txtProjectPath.Text = previousProjectPath;
                }
                rdbFolder.Checked = true;
                lblCurrentProject.Text = "";
            }
            else
            {
                rdbCurrentProject.Checked = true;
                lblCurrentProject.Text = _prj.ProjectFolder;
            }

            //wind direction status
            if (_prj != null && _prj.WindDirection != -1)
            {
                cmbxWindDir.SelectedIndex = _prj.WindDirection;                
                if(_spatialAnalystExtention)
                    gbWindDirection.Enabled = true;
            }
            else
            {
                cmbxWindDir.SelectedIndex = 3;  //default is northwest
            }

            //get all the SWAT exes under installation folder\swat_exes
            //user could copy any swat.exe to this folder to run
            string swatExeFolder = CanSWAT.InstallationFolder + "swat_exes";
            if (Directory.Exists(swatExeFolder))
            {
                DirectoryInfo info = new DirectoryInfo(swatExeFolder);
                FileInfo[] files = info.GetFiles("*.exe");
                foreach (FileInfo f in files)
                    cmbSwatExeList.Items.Add(f.Name);

                if (cmbSwatExeList.Items.Count > 0)
                    cmbSwatExeList.SelectedIndex = 0;
                else
                    cmbSwatExeList.Enabled = false;
             }
            else
                cmbSwatExeList.Enabled = false;
        }

        private void bSetWindDirection_Click(object sender, EventArgs e)
        {
            if (checkProject())
            {
                //check the spatial analyst
                if (!_spatialAnalystExtention)
                {
                    CanSWAT.showInformationWindow("The spatial analyst extension is not available in your computer. The wind direction can't be set.");
                    return;
                }

                if (_prj.WindDirection == cmbxWindDir.SelectedIndex)
                {
                    if (System.Windows.Forms.MessageBox.Show(
                        "The wind direction you select is same with previous setting. Do you want to re-write all the slope and curvature?", CanSWAT.CAN_SWAT_TITLE, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        setWinddirection();
                }
                else setWinddirection();
            }
        }

        private void setWinddirection()
        {
            txtProgress.Text += "ArcSWAT Project: " + _prj.ProjectFolder;
            txtProgress.Text += Environment.NewLine;
            _prj.WindDirection = cmbxWindDir.SelectedIndex;
            CanSWAT.showInformationWindow("Wind direction is set.");
        }

        private void bBrowseProject_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                _prj = new ArcSWAT.Project(folderBrowserDialog1.SelectedPath);
                _prj.ProgressChanged += new EventHandler(onProjectProgressChanged);
                if (!_prj.IsValid)
                {
                    _prj = null;
                    CanSWAT.showInformationWindow(folderBrowserDialog1.SelectedPath + " is not a valid ArcSWAT project folder. Please check following items." + 
                        "\n1. Project mxd file and mdb file" + 
                        "\n2. SWAT2009.mdb for ArcSWAT 2009 or SWAT2012.mdb for ArcSWAT 2012" + 
                        "\n3. If the HRU polygon is created during Land use/Soil/Slope Definition and Overlayer and the FullHRU table exists in project mdb.");
                    return;
                }
                txtProjectPath.Text = folderBrowserDialog1.SelectedPath;
                if(_spatialAnalystExtention)
                    gbWindDirection.Enabled = true;
                
                if (_prj.WindDirection != -1)
                    cmbxWindDir.SelectedIndex = _prj.WindDirection;
                else
                    cmbxWindDir.SelectedIndex = 3;  //default is northwest

                //save current path
                Properties.Settings.Default.PreviousProjectFolder = folderBrowserDialog1.SelectedPath;
                Properties.Settings.Default.Save();
            }
        }

        private void bWriteInputFiles_Click(object sender, EventArgs e)
        {
            if (_prj != null)
            {
                try
                {
                    _prj.write();
                    CanSWAT.showInformationWindow(
                        "Write " + _prj.DefaultSWATModel.SnowRedistribution.getFileName(SWAT.SnowRedistributionFileType.HRUParameter));
                }
                catch (System.Exception ee)
                {
                    CanSWAT.showInformationWindow(ee.Message);
                }
            }
        }

        private void onProjectProgressChanged(object sender, EventArgs e)
        {
            ArcSWAT.BaseWithProcess p = sender as ArcSWAT.BaseWithProcess;
 
            progressBar1.Value = p.ProcessPercentage;
            txtProgress.Text += p.ProcessMessage;
            txtProgress.Text += Environment.NewLine; 
        }

        private bool checkProject()
        {
            if (_prj == null)
                CanSWAT.showInformationWindow("Please open a project first.");

            return _prj != null;
        }

        private void bOpenSnowRedistributionFile_Click(object sender, EventArgs e)
        {
            if(checkProject())
                _prj.DefaultSWATModel.SnowRedistribution.Edit(SWAT.SnowRedistributionFileType.HRUParameter);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (checkProject())
                _prj.DefaultSWATModel.SnowRedistribution.Edit(SWAT.SnowRedistributionFileType.GeneralParameter);
        }

        private void bOpenFrozenSoilTxt_Click(object sender, EventArgs e)
        {
            if (checkProject())
                _prj.DefaultSWATModel.FrozenSoil.Edit();
        }

        private void bGenerateElevationBand_Click(object sender, EventArgs e)
        {
            if (checkProject())
                _prj.GenerateElevationBands();
        }

        private void bOpenElevationBand_Click(object sender, EventArgs e)
        {
            if (checkProject())
                _prj.DisplayElevationBands();
        }

        private void bEditSHC_Click(object sender, EventArgs e)
        {
            if (checkProject())
                _prj.ProjectDatabase.EditSnowHoldingCapacity();
        }

        private void bRunDirectly_Click(object sender, EventArgs e)
        {
            if (checkProject() && cmbSwatExeList.Enabled)
                _prj.DefaultSWATModel.RunSWAT(cmbSwatExeList.SelectedItem.ToString());
        }

        private void bOpenModelFolder_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(_prj.DefaultSWATModel.Folder);
        }

        private void bSetupSWATRun_Click(object sender, EventArgs e)
        {
            //open ArcSWAT "Setup and run SWAT model simulation" window to setup model run
            if(onSetupSWATRun != null)
                onSetupSWATRun(this, new EventArgs());
        }

        private void bReadOutput_Click(object sender, EventArgs e)
        {
            //open ArcSWAT "Read SWAT output" window to read outputs to mdb
            if (onReadSWATOutput != null)
                onReadSWATOutput(this, new EventArgs());
        }

        public event EventHandler onSetupSWATRun;
        public event EventHandler onReadSWATOutput;

        private void bRunInSwatEditor_Click(object sender, EventArgs e)
        {
            if (checkProject())
                _prj.RunSWATEditor();
        }

        private void bSWATCheck_Click(object sender, EventArgs e)
        {
            if (checkProject())
                _prj.DefaultSWATModel.Check(_prj.SWATType);
        }

        private void bResult_Click(object sender, EventArgs e)
        {
            CanSWAT.Run("SWATResultDisplay.exe",
                "\"" + _prj.ProjectFolder + @"\Scenarios\Default\TablesOut\SWATOutput.mdb" + "\"");
        }


    }
}
